package com.rickpan.socketio;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.rickpan.entity.Team;
import com.rickpan.entity.TeamMember;
import com.rickpan.entity.TeamMessage;
import com.rickpan.entity.User;
import com.rickpan.service.TeamService;
import com.rickpan.service.TeamMemberService;
import com.rickpan.repository.UserRepository;
import com.rickpan.repository.TeamMessageRepository;
import com.rickpan.dto.request.TeamMessageRequest;
import com.rickpan.dto.response.TeamMessageDTO;
import com.rickpan.event.TeamMessageEvent;
import com.rickpan.event.TeamMemberOnlineEvent;
import com.rickpan.service.TeamMessageProducer;
import com.rickpan.service.MessageRoutingService;
import com.rickpan.service.MessageRetryService;
import com.rickpan.service.DynamicConsumerManager;
import com.rickpan.service.DynamicConsumerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 团队协作事件处理器
 * 处理团队聊天、成员在线状态、项目协作等实时事件
 */
@Component
public class TeamEventHandler {

    private static final Logger logger = LoggerFactory.getLogger(TeamEventHandler.class);

    @Autowired
    private SocketIOServer socketIOServer;

    @Autowired
    private TeamService teamService;

    @Autowired
    private TeamMemberService teamMemberService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TeamMessageRepository teamMessageRepository;

    // RabbitMQ消息生产者（条件注入，只有在RabbitMQ可用时才注入）
    @Autowired(required = false)
    private TeamMessageProducer teamMessageProducer;

    // 消息路由服务（条件注入）
    @Autowired(required = false)
    private MessageRoutingService messageRoutingService;

    // 消息重试服务（条件注入）
    @Autowired(required = false)
    private MessageRetryService messageRetryService;

    // 动态消费者管理器（条件注入）
    @Autowired(required = false)
    private DynamicConsumerManager dynamicConsumerManager;

    // 存储用户ID与Socket客户端的映射关系
    private final Map<Long, SocketIOClient> userClientMap = new ConcurrentHashMap<>();
    
    // 存储团队房间与成员的映射关系
    private final Map<Long, Set<Long>> teamMembersMap = new ConcurrentHashMap<>();
    
    // 存储用户与团队的映射关系
    private final Map<Long, Set<Long>> userTeamsMap = new ConcurrentHashMap<>();

    /**
     * 客户端连接事件
     */
    @OnConnect
    public void onConnect(SocketIOClient client) {
        try {
            String userIdStr = client.getHandshakeData().getSingleUrlParam("userId");
            if (userIdStr == null || userIdStr.isEmpty()) {
                logger.warn("❌ 连接被拒绝：缺少userId参数");
                client.disconnect();
                return;
            }

            Long userId = Long.valueOf(userIdStr);
            
            // 验证用户是否存在
            User user = userRepository.findById(userId).orElse(null);
            if (user == null) {
                logger.warn("❌ 连接被拒绝：用户不存在 userId={}", userId);
                client.disconnect();
                return;
            }

            // 存储用户连接映射
            userClientMap.put(userId, client);

            // 创建用户的RabbitMQ消费者（如果RabbitMQ可用）
            if (dynamicConsumerManager != null) {
                try {
                    dynamicConsumerManager.createUserConsumer(userId);
                    logger.info("✅ 用户RabbitMQ消费者创建成功: userId={}", userId);
                } catch (Exception e) {
                    logger.error("❌ 用户RabbitMQ消费者创建失败: userId={}", userId, e);
                }
            }

            // 加入用户的所有团队房间
            joinUserTeams(userId, client);

            // 发送连接成功确认
            client.sendEvent("team_connected", createMap(
                "status", "success",
                "message", "团队协作连接成功",
                "userId", userId,
                "timestamp", System.currentTimeMillis()
            ));

            // 通知团队成员用户上线
            notifyTeamMembersUserOnline(userId, true);

            logger.info("✅ 团队协作连接成功 userId={}, sessionId={}", userId, client.getSessionId());

        } catch (Exception e) {
            logger.error("❌ 处理连接事件失败", e);
            client.disconnect();
        }
    }

    /**
     * 客户端断开连接事件
     */
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        try {
            // 查找断开连接的用户
            Long userId = findUserIdByClient(client);
            if (userId != null) {
                // 清理用户连接映射
                userClientMap.remove(userId);

                // 销毁用户的RabbitMQ消费者（如果RabbitMQ可用）
                if (dynamicConsumerManager != null) {
                    try {
                        dynamicConsumerManager.destroyUserConsumer(userId);
                        logger.info("✅ 用户RabbitMQ消费者销毁成功: userId={}", userId);
                    } catch (Exception e) {
                        logger.error("❌ 用户RabbitMQ消费者销毁失败: userId={}", userId, e);
                    }
                }

                // 离开所有团队房间
                leaveUserTeams(userId);

                // 通知团队成员用户下线
                notifyTeamMembersUserOnline(userId, false);

                logger.info("🔌 团队协作连接断开 userId={}, sessionId={}", userId, client.getSessionId());
            }
        } catch (Exception e) {
            logger.error("❌ 处理断开连接事件失败", e);
        }
    }

    /**
     * 发送团队消息事件
     */
    @OnEvent("send_team_message")
    public void onSendTeamMessage(SocketIOClient client, TeamMessageRequest request) {
        try {
            Long userId = findUserIdByClient(client);
            if (userId == null) {
                client.sendEvent("error", createMap("message", "用户未认证"));
                return;
            }

            // 验证用户是否为团队成员
            if (!teamMemberService.isTeamMember(request.getTeamId(), userId)) {
                client.sendEvent("error", createMap("message", "您不是该团队成员"));
                return;
            }

            // 创建消息DTO
            TeamMessageDTO messageDTO = new TeamMessageDTO();
            messageDTO.setTeamId(request.getTeamId());
            messageDTO.setSenderId(userId);
            messageDTO.setContent(request.getContent());
            messageDTO.setMessageType(request.getMessageType());
            messageDTO.setTimestamp(System.currentTimeMillis());

            // 设置加密相关字段
            messageDTO.setIv(request.getIv());
            messageDTO.setEncryptionAlgorithm(request.getEncryptionAlgorithm());
            messageDTO.setKeyVersion(request.getKeyVersion());
            messageDTO.setIsEncrypted(request.getIsEncrypted());

            // 记录加密状态
            if (request.getIsEncrypted() != null && request.getIsEncrypted()) {
                logger.info("🔐 接收到加密消息: teamId={}, algorithm={}, keyVersion={}, hasIV={}",
                           request.getTeamId(), request.getEncryptionAlgorithm(),
                           request.getKeyVersion(), request.getIv() != null);
            }

            // 获取发送者信息
            User sender = userRepository.findById(userId).orElse(null);
            if (sender != null) {
                messageDTO.setSenderName(sender.getUsername());
                messageDTO.setSenderAvatar(sender.getAvatarUrl());
            }

            // 保存消息到数据库
            TeamMessage message = new TeamMessage();
            message.setTeamId(request.getTeamId());
            message.setSenderId(userId);
            message.setMessageType(TeamMessage.MessageType.valueOf(request.getMessageType()));
            message.setContent(request.getContent());
            message.setMessageStatus(TeamMessage.MessageStatus.sent);

            // 设置加密相关字段
            message.setIv(request.getIv());
            message.setEncryptionAlgorithm(request.getEncryptionAlgorithm());
            message.setKeyVersion(request.getKeyVersion());
            message.setIsEncrypted(request.getIsEncrypted() != null ? request.getIsEncrypted() : false);

            // 处理文件消息
            if ("file".equals(request.getMessageType()) || "image".equals(request.getMessageType())) {
                logger.info("📁 处理文件消息: messageType={}, fileName={}, fileSize={}, fileUrl={}",
                           request.getMessageType(), request.getFileName(), request.getFileSize(), request.getFileUrl());

                message.setFileName(request.getFileName());
                message.setFileSize(request.getFileSize());
                message.setFileUrl(request.getFileUrl());

                // 同时设置DTO的文件信息（用于Socket广播）
                messageDTO.setFileName(request.getFileName());
                messageDTO.setFileSize(request.getFileSize());
                messageDTO.setFileUrl(request.getFileUrl());

                logger.info("✅ 文件信息已设置到DTO: fileName={}, fileSize={}, fileUrl={}",
                           messageDTO.getFileName(), messageDTO.getFileSize(), messageDTO.getFileUrl());
            }

            // 保存到数据库
            TeamMessage savedMessage = teamMessageRepository.save(message);
            messageDTO.setId(savedMessage.getId());

            // 🚀 RabbitMQ集成：使用路由服务发送消息（如果RabbitMQ可用）
            if (messageRoutingService != null) {
                try {
                    MessageRoutingService.MessageRoutingResult result = messageRoutingService.routeTeamMessage(messageDTO);

                    if (result.isSuccess()) {
                        logger.info("📤 消息路由成功: teamId={}, messageId={}, strategy={}",
                                   request.getTeamId(), savedMessage.getId(), result.getStrategy());
                    } else if (result.isDuplicate()) {
                        logger.warn("⚠️ 重复消息，跳过处理: teamId={}, messageId={}",
                                   request.getTeamId(), savedMessage.getId());
                    } else {
                        // 路由失败，直接降级到Socket.IO（暂时禁用重试机制）
                        logger.warn("⚠️ 消息路由失败，直接使用Socket.IO广播: teamId={}, messageId={}",
                                   request.getTeamId(), savedMessage.getId());
                        broadcastToTeamExcept(request.getTeamId(), userId, "new_team_message", messageDTO);

                        /* 暂时禁用重试机制，直接降级到Socket.IO
                        if (messageRetryService != null) {
                            messageRetryService.handleMessageFailure(messageDTO, result.getException());
                        } else {
                            // 重试服务不可用，直接回退到Socket.IO
                            logger.warn("⚠️ 消息路由失败且重试服务不可用，使用Socket.IO直接广播: teamId={}, messageId={}",
                                       request.getTeamId(), savedMessage.getId());
                            broadcastToTeamExcept(request.getTeamId(), userId, "new_team_message", messageDTO);
                        }
                        */
                    }

                } catch (Exception e) {
                    logger.error("❌ 消息路由异常，使用Socket.IO直接广播: teamId={}, messageId={}",
                                request.getTeamId(), savedMessage.getId(), e);
                    broadcastToTeamExcept(request.getTeamId(), userId, "new_team_message", messageDTO);
                }
            } else {
                // RabbitMQ不可用时，直接使用Socket.IO广播
                logger.info("📡 RabbitMQ不可用，使用Socket.IO直接广播: teamId={}, messageId={}",
                           request.getTeamId(), savedMessage.getId());
                broadcastToTeamExcept(request.getTeamId(), userId, "new_team_message", messageDTO);
            }

            // 向发送者确认消息发送成功
            logger.info("✅ 向发送者确认消息发送成功 userId={}, messageId={}", userId, savedMessage.getId());
            client.sendEvent("message_sent", createMap(
                "messageId", savedMessage.getId(),
                "status", "success",
                "timestamp", System.currentTimeMillis()
            ));

            logger.info("📨 团队消息发送成功 teamId={}, userId={}, messageType={}, messageId={}",
                       request.getTeamId(), userId, request.getMessageType(), savedMessage.getId());

        } catch (Exception e) {
            logger.error("❌ 发送团队消息失败", e);
            client.sendEvent("error", createMap("message", "发送消息失败"));
        }
    }

    /**
     * 获取团队在线成员事件
     */
    @OnEvent("get_team_online_members")
    public void onGetTeamOnlineMembers(SocketIOClient client, Map<String, Object> data) {
        try {
            Long userId = findUserIdByClient(client);
            if (userId == null) {
                client.sendEvent("error", createMap("message", "用户未认证"));
                return;
            }

            Object teamIdObj = data.get("teamId");
            if (teamIdObj == null) {
                client.sendEvent("error", createMap("message", "缺少teamId参数"));
                return;
            }
            Long teamId = Long.valueOf(teamIdObj.toString());

            // 验证用户是否为团队成员
            if (!teamMemberService.isTeamMember(teamId, userId)) {
                client.sendEvent("error", createMap("message", "您不是该团队成员"));
                return;
            }

            // 获取团队在线成员
            Set<Long> onlineMembers = getTeamOnlineMembers(teamId);
            
            // 获取成员详细信息
            List<Map<String, Object>> memberDetails = onlineMembers.stream()
                .map(memberId -> {
                    User user = userRepository.findById(memberId).orElse(null);
                    Map<String, Object> memberInfo = new HashMap<>();
                    memberInfo.put("userId", memberId);
                    if (user != null) {
                        memberInfo.put("username", user.getUsername());
                        memberInfo.put("avatarUrl", user.getAvatarUrl() != null ? user.getAvatarUrl() : "");
                    } else {
                        memberInfo.put("username", "Unknown User");
                        memberInfo.put("avatarUrl", "");
                    }
                    memberInfo.put("isOnline", true);
                    return memberInfo;
                })
                .collect(Collectors.toList());

            client.sendEvent("team_online_members", createMap(
                "teamId", teamId,
                "members", memberDetails,
                "count", onlineMembers.size()
            ));

        } catch (Exception e) {
            logger.error("❌ 获取团队在线成员失败", e);
            client.sendEvent("error", createMap("message", "获取在线成员失败"));
        }
    }

    /**
     * 加入团队房间事件
     */
    @OnEvent("join_team")
    public void onJoinTeam(SocketIOClient client, Map<String, Object> data) {
        try {
            Long userId = findUserIdByClient(client);
            if (userId == null) {
                client.sendEvent("error", createMap("message", "用户未认证"));
                return;
            }

            Long teamId = Long.valueOf(data.get("teamId").toString());

            // 验证用户是否为团队成员
            if (!teamMemberService.isTeamMember(teamId, userId)) {
                client.sendEvent("error", createMap("message", "您不是该团队成员"));
                return;
            }

            // 加入团队房间
            client.joinRoom("team_" + teamId);
            
            // 更新团队成员映射
            teamMembersMap.computeIfAbsent(teamId, k -> ConcurrentHashMap.newKeySet()).add(userId);
            userTeamsMap.computeIfAbsent(userId, k -> ConcurrentHashMap.newKeySet()).add(teamId);

            // 通知团队其他成员
            broadcastToTeamExcept(teamId, userId, "member_joined_team", createMap(
                "teamId", teamId,
                "userId", userId,
                "timestamp", System.currentTimeMillis()
            ));

            client.sendEvent("joined_team", createMap(
                "teamId", teamId,
                "status", "success"
            ));

            logger.info("👥 用户加入团队房间 userId={}, teamId={}", userId, teamId);

        } catch (Exception e) {
            logger.error("❌ 加入团队房间失败", e);
            client.sendEvent("error", createMap("message", "加入团队失败"));
        }
    }

    /**
     * 离开团队房间事件
     */
    @OnEvent("leave_team")
    public void onLeaveTeam(SocketIOClient client, Map<String, Object> data) {
        try {
            Long userId = findUserIdByClient(client);
            if (userId == null) {
                return;
            }

            Long teamId = Long.valueOf(data.get("teamId").toString());
            
            // 离开团队房间
            client.leaveRoom("team_" + teamId);
            
            // 更新团队成员映射
            Set<Long> teamMembers = teamMembersMap.get(teamId);
            if (teamMembers != null) {
                teamMembers.remove(userId);
            }
            
            Set<Long> userTeams = userTeamsMap.get(userId);
            if (userTeams != null) {
                userTeams.remove(teamId);
            }

            // 通知团队其他成员
            broadcastToTeamExcept(teamId, userId, "member_left_team", createMap(
                "teamId", teamId,
                "userId", userId,
                "timestamp", System.currentTimeMillis()
            ));

            logger.info("👋 用户离开团队房间 userId={}, teamId={}", userId, teamId);

        } catch (Exception e) {
            logger.error("❌ 离开团队房间失败", e);
        }
    }

    // ==================== 私有辅助方法 ====================

    /**
     * 创建Map的辅助方法，避免类型推断问题
     */
    private Map<String, Object> createMap(Object... keyValuePairs) {
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < keyValuePairs.length; i += 2) {
            map.put((String) keyValuePairs[i], keyValuePairs[i + 1]);
        }
        return map;
    }

    /**
     * 根据客户端查找用户ID
     */
    private Long findUserIdByClient(SocketIOClient client) {
        return userClientMap.entrySet().stream()
            .filter(entry -> entry.getValue().getSessionId().equals(client.getSessionId()))
            .map(Map.Entry::getKey)
            .findFirst()
            .orElse(null);
    }

    /**
     * 加入用户的所有团队房间
     */
    private void joinUserTeams(Long userId, SocketIOClient client) {
        try {
            List<TeamMember> userTeams = teamMemberService.findActiveTeamsByUserId(userId);
            Set<Long> teamIds = ConcurrentHashMap.newKeySet();
            
            for (TeamMember teamMember : userTeams) {
                Long teamId = teamMember.getTeamId();
                client.joinRoom("team_" + teamId);
                teamIds.add(teamId);
                
                // 更新团队成员映射
                teamMembersMap.computeIfAbsent(teamId, k -> ConcurrentHashMap.newKeySet()).add(userId);
            }
            
            // 更新用户团队映射
            userTeamsMap.put(userId, teamIds);
            
            logger.info("👥 用户加入 {} 个团队房间 userId={}", teamIds.size(), userId);
            
        } catch (Exception e) {
            logger.error("❌ 加入用户团队房间失败 userId={}", userId, e);
        }
    }

    /**
     * 离开用户的所有团队房间
     */
    private void leaveUserTeams(Long userId) {
        Set<Long> userTeams = userTeamsMap.remove(userId);
        if (userTeams != null) {
            for (Long teamId : userTeams) {
                Set<Long> teamMembers = teamMembersMap.get(teamId);
                if (teamMembers != null) {
                    teamMembers.remove(userId);
                }
            }
        }
    }

    /**
     * 广播消息到团队所有成员
     * 供RabbitMQ消费者调用
     */
    public void broadcastToTeam(Long teamId, String eventName, Object data) {
        logger.info("📡 RabbitMQ消费者请求广播: teamId={}, eventName={}", teamId, eventName);
        socketIOServer.getRoomOperations("team_" + teamId).sendEvent(eventName, data);
        logger.info("✅ RabbitMQ消费者广播完成: teamId={}", teamId);
    }

    /**
     * 广播消息到团队所有成员（排除指定用户）
     */
    private void broadcastToTeamExcept(Long teamId, Long excludeUserId, String eventName, Object data) {
        Set<Long> teamMembers = teamMembersMap.get(teamId);

        if (teamMembers != null && !teamMembers.isEmpty()) {
            // 使用团队成员映射广播
            logger.info("📡 使用团队成员映射广播: teamId={}, memberCount={}, excludeUserId={}",
                       teamId, teamMembers.size(), excludeUserId);
            teamMembers.stream()
                .filter(memberId -> !memberId.equals(excludeUserId))
                .forEach(memberId -> {
                    SocketIOClient client = userClientMap.get(memberId);
                    if (client != null && client.isChannelOpen()) {
                        client.sendEvent(eventName, data);
                        logger.debug("📤 消息已发送给用户: userId={}", memberId);
                    } else {
                        logger.debug("⚠️ 用户客户端不可用: userId={}", memberId);
                    }
                });
        } else {
            // 团队成员映射为空，使用备用方案：广播给所有在线用户
            logger.warn("⚠️ 团队成员映射为空，使用备用广播方案: teamId={}, onlineUsers={}",
                       teamId, userClientMap.size());

            userClientMap.entrySet().stream()
                .filter(entry -> !entry.getKey().equals(excludeUserId))
                .forEach(entry -> {
                    Long userId = entry.getKey();
                    SocketIOClient client = entry.getValue();
                    if (client != null && client.isChannelOpen()) {
                        // 验证用户是否为团队成员
                        try {
                            if (teamMemberService.isTeamMember(teamId, userId)) {
                                client.sendEvent(eventName, data);
                                logger.debug("📤 备用方案消息已发送给用户: userId={}", userId);
                            }
                        } catch (Exception e) {
                            logger.debug("⚠️ 验证团队成员关系失败: userId={}, teamId={}", userId, teamId);
                        }
                    }
                });
        }
    }

    /**
     * 获取团队在线成员
     */
    private Set<Long> getTeamOnlineMembers(Long teamId) {
        return teamMembersMap.getOrDefault(teamId, Collections.emptySet());
    }

    /**
     * 通知团队成员用户上线/下线状态
     */
    private void notifyTeamMembersUserOnline(Long userId, boolean isOnline) {
        Set<Long> userTeams = userTeamsMap.get(userId);
        if (userTeams != null) {
            for (Long teamId : userTeams) {
                broadcastToTeamExcept(teamId, userId, "member_online_status", createMap(
                    "userId", userId,
                    "isOnline", isOnline,
                    "timestamp", System.currentTimeMillis()
                ));
            }
        }
    }

    // ==================== RabbitMQ消费者调用方法 ====================

    /**
     * 广播团队消息（供RabbitMQ消费者调用）
     * 这个方法将被TeamMessageConsumer调用，用于广播从队列消费的消息
     *
     * @param messageDTO 团队消息DTO
     */
    public void broadcastTeamMessageFromQueue(TeamMessageDTO messageDTO) {
        try {
            logger.info("📡 从RabbitMQ队列广播团队消息: teamId={}, messageId={}",
                       messageDTO.getTeamId(), messageDTO.getId());

            // 广播消息到团队房间（包括发送者，因为这是从队列消费的消息）
            broadcastToTeam(messageDTO.getTeamId(), "new_team_message", messageDTO);

            logger.info("✅ 队列消息广播成功: teamId={}, messageId={}",
                       messageDTO.getTeamId(), messageDTO.getId());

        } catch (Exception e) {
            logger.error("❌ 队列消息广播失败: teamId={}, messageId={}",
                        messageDTO.getTeamId(), messageDTO.getId(), e);
            throw e;
        }
    }

    /**
     * 向特定用户发送团队消息（供RabbitMQ消费者调用）
     * 这个方法将被TeamMessageConsumer调用，用于向特定用户发送从队列消费的消息
     *
     * @param messageDTO 团队消息DTO
     * @param userId 目标用户ID
     */
    public void broadcastTeamMessageToUser(TeamMessageDTO messageDTO, Long userId) {
        try {
            logger.info("📡 从RabbitMQ队列向用户发送团队消息: userId={}, teamId={}, messageId={}",
                       userId, messageDTO.getTeamId(), messageDTO.getId());

            // 获取用户的Socket连接
            SocketIOClient userClient = userClientMap.get(userId);
            if (userClient != null && userClient.isChannelOpen()) {
                // 发送消息给特定用户
                userClient.sendEvent("new_team_message", messageDTO);

                logger.info("✅ 用户队列消息发送成功: userId={}, teamId={}, messageId={}",
                           userId, messageDTO.getTeamId(), messageDTO.getId());
            } else {
                logger.debug("⚠️ 用户未连接或连接已断开: userId={}, teamId={}, messageId={}",
                           userId, messageDTO.getTeamId(), messageDTO.getId());
            }

        } catch (Exception e) {
            logger.error("❌ 用户队列消息发送失败: userId={}, teamId={}, messageId={}",
                        userId, messageDTO.getTeamId(), messageDTO.getId(), e);
            throw e;
        }
    }

    /**
     * 广播用户通知（供RabbitMQ消费者调用）
     *
     * @param userId 用户ID
     * @param notification 通知内容
     */
    public void broadcastUserNotificationFromQueue(Long userId, Object notification) {
        try {
            SocketIOClient client = userClientMap.get(userId);
            if (client != null) {
                client.sendEvent("user_notification", notification);
                logger.info("📤 用户通知广播成功: userId={}", userId);
            } else {
                logger.warn("⚠️ 用户不在线，通知未发送: userId={}", userId);
            }
        } catch (Exception e) {
            logger.error("❌ 用户通知广播失败: userId={}", userId, e);
            throw e;
        }
    }

    /**
     * 广播系统消息（供RabbitMQ消费者调用）
     *
     * @param broadcastMessage 广播消息
     */
    public void broadcastSystemMessageFromQueue(Object broadcastMessage) {
        try {
            // 向所有在线用户广播系统消息
            socketIOServer.getBroadcastOperations().sendEvent("system_broadcast", broadcastMessage);
            logger.info("📢 系统广播成功: 在线用户数={}", userClientMap.size());
        } catch (Exception e) {
            logger.error("❌ 系统广播失败", e);
            throw e;
        }
    }

    /**
     * 检查RabbitMQ是否可用
     *
     * @return 是否可用
     */
    public boolean isRabbitMQAvailable() {
        return teamMessageProducer != null;
    }

    // ==================== 监控和统计方法 ====================

    /**
     * 获取消息路由统计信息
     *
     * @return 路由统计
     */
    public Map<String, Long> getMessageRoutingStats() {
        if (messageRoutingService != null) {
            return messageRoutingService.getRoutingStats();
        }
        return new java.util.HashMap<>();
    }

    /**
     * 获取消息重试统计信息
     *
     * @return 重试统计
     */
    public Map<String, Integer> getMessageRetryStats() {
        if (messageRetryService != null) {
            return messageRetryService.getRetryStats();
        }
        return new java.util.HashMap<>();
    }

    /**
     * 获取死信消息列表
     *
     * @return 死信消息
     */
    public Map<String, MessageRetryService.DeadLetterRecord> getDeadLetterMessages() {
        if (messageRetryService != null) {
            return messageRetryService.getAllDeadLetters();
        }
        return new java.util.HashMap<>();
    }

    /**
     * 手动重新处理死信消息
     *
     * @param messageKey 消息键
     * @return 是否成功
     */
    public boolean reprocessDeadLetterMessage(String messageKey) {
        if (messageRetryService != null) {
            return messageRetryService.reprocessDeadLetter(messageKey);
        }
        return false;
    }

    /**
     * 获取系统健康状态
     *
     * @return 健康状态
     */
    public Map<String, Object> getSystemHealthStatus() {
        Map<String, Object> status = new java.util.HashMap<>();

        // Socket.IO状态
        status.put("socketio_online_users", userClientMap.size());
        status.put("socketio_active_teams", teamMembersMap.size());

        // RabbitMQ状态
        status.put("rabbitmq_available", isRabbitMQAvailable());

        // 路由统计
        if (messageRoutingService != null) {
            status.put("routing_stats", messageRoutingService.getRoutingStats());
        }

        // 重试统计
        if (messageRetryService != null) {
            status.put("retry_stats", messageRetryService.getRetryStats());
            status.put("dead_letter_count", messageRetryService.getAllDeadLetters().size());
        }

        return status;
    }

    /**
     * 重置所有统计信息
     */
    public void resetAllStats() {
        if (messageRoutingService != null) {
            messageRoutingService.resetRoutingStats();
        }
        if (messageRetryService != null) {
            messageRetryService.resetStats();
        }
        logger.info("📊 所有统计信息已重置");
    }
}
